package com.gjy.util.concurrent;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveAction;

/**
 * 多线程批处理数据
 *
 * @author 宫静雨
 * @version 1.0
 * @since 2023-10-23 16:50:02
 */
public class RecursiveActionImpl extends RecursiveAction {

    private static final Logger log = LoggerFactory.getLogger(RecursiveActionImpl.class);

    //设置批量处理数据量临界值
    private static final int THRESHOLD = 10000;

    private final List<Integer> list;

    public RecursiveActionImpl(List<Integer> list) {
        this.list = list;
    }

    @Override
    protected void compute() {
        boolean flag = list.size() < THRESHOLD;
        if (flag) {
            // 处理集合数据
            log.info("list: {}", list.size());
        } else {
            // Lists.partition(list,2)
            List<List<Integer>> lists = averageAssign(list, 2);
            RecursiveActionImpl r1 = new RecursiveActionImpl(lists.get(0));
            RecursiveActionImpl r2 = new RecursiveActionImpl(lists.get(1));
            invokeAll(r1, r2);
        }
    }

    /**
     * 将一组数据平均分成n组
     *
     * @param source 要分组的数据源
     * @param n      平均分成n组
     * @param <T>    泛型
     * @return 拆分后的集合
     */
    public <T> List<List<T>> averageAssign(List<T> source, int n) {
        List<List<T>> result = new ArrayList<>();
        //(先计算出余数)
        int remainder = source.size() % n;
        //然后是商
        int number = source.size() / n;
        //偏移量
        int offset = 0;
        for (int i = 0; i < n; i++) {
            List<T> value;
            if (remainder > 0) {
                value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
                remainder--;
                offset++;
            } else {
                value = source.subList(i * number + offset, (i + 1) * number + offset);
            }
            result.add(value);
        }
        return result;
    }

}
